<template>
	<view>
		<view class="fixed">
			<!-- 状态栏 -->
			<view class="statusBar" :style="'height:'+statusBarHeight+'px'"></view>
			<view class="myheader padding-sm font-sub-title">
				<text class="cuIcon-back margin-right-ssm" @click="back()"></text>
				个人信息
			</view>
		</view>
		<view class="cu-list menu sm-border" :style="{marginTop:navHeight}">
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">头像</text>
				</view>
				<view class="action" @click="changeAvatar()">
					<jy-image placeholder="/static/loading.gif" class="cu-avatar round margin-left" :src="avatar" mode="aspectFill"></jy-image>
				</view>
			</view>
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">姓名</text>
				</view>
				<view class="action">
					<input class="font-normal my_input" maxlength="10" v-model="name" placeholder="请输入姓名"/>
				</view>
			</view>
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">生日</text>
				</view>
				<picker class="action" mode="date" :value="birthday" @change="bindDateChange">
					<view class="my_input font-normal">{{birthday}}</view>
				</picker>
			</view>
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">性别</text>
				</view>
				<picker mode="selector" :value="sexIndex" :range="sexArray" @change="bindSexChange">
					<view class="my_input font-normal">{{sexArray[sexIndex]}}</view>
				</picker>
			</view>
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">身份证</text>
				</view>
				<view class="action">
					<input v-model="idCard" class="font-normal my_input" placeholder="请输入身份证号"/>
				</view>
			</view>
			<view class="grace-idcard-main">
				<view class="grace-idcard-text font-normal text-light-gray">
					身份证照片 ( 正面 )
				</view>
				<view class="grace-idcard-items">
					<view class="grace-idcard-uper-btn" @click="selectImg1">
						<view class="img"><image src="../../static/img/camera.png" mode="widthFix" /></view>
						<view class="text">拍摄或选择照片</view>
					</view>
					<view class="grace-idcard-preview">
						<jy-image placeholder="/static/loading.gif" :src="idCard1"  @click="previewImg1" mode="aspectFill"></jy-image>
					</view>
				</view>
				<view class="grace-idcard-text font-normal text-light-gray">
					身份证照片 ( 背面 )
				</view>
				<view class="grace-idcard-items">
					<view class="grace-idcard-uper-btn" @click="selectImg2">
						<view class="img"><image src="../../static/img/camera.png" mode="widthFix" /></view>
						<view class="text">拍摄或选择照片</view>
					</view>
					<view class="grace-idcard-preview">
						<jy-image placeholder="/static/loading.gif" :src="idCard2" @click="previewImg2" mode="aspectFill"></jy-image>
					</view>
				</view>
			</view>
			<!-- <view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">手机</text>
				</view>
				<view class="action">
					<text class=" font-normal">13771504600</text>
				</view>
			</view> -->
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">省份</text>
				</view>
				<view class="action">
					<picker class="action" mode="selector" :range="provinceList" :range-key="'regionName'" :value="provinceIndex" @change="bindProvinceChange">
						<text class=" font-normal">{{provinceList[provinceIndex].regionName}}</text>
					</picker>
				</view>
			</view>
			<view class="cu-item bg-white arrow" v-if="provinceIndex!=0">
				<view class="content">
					<text class="font-normal">城市</text>
				</view>
				<view class="action">
					<picker class="action" mode="selector" :range="cityList" :range-key="'regionName'"  :value="cityIndex" @change="bindCityChange">
						<text class=" font-normal">{{cityList[cityIndex].regionName}}</text>
					</picker>
				</view>
			</view>
			<view class="cu-item bg-white arrow" v-if="cityIndex!=0&&flag">
				<view class="content">
					<text class="font-normal">市区</text>
				</view>
				<view class="action">
					<picker class="action" mode="selector" :range="districtList" :range-key="'regionName'"  :value="districtIndex" @change="bindDistrictChange">
						<text class=" font-normal">{{districtList[districtIndex].regionName}}</text>
					</picker>
				</view>
			</view>
			<view class="cu-item bg-white arrow">
				<view class="content">
					<text class="font-normal">详细地址</text>
				</view>
				<view class="action">
					<input v-model="address" class=" font-normal my_input" placeholder="请输入详细地址"/>
				</view>
			</view>
		</view>
		<view class="text-center save_btn">
			<button class="cu-btn login-btn font-normal" @click="save()">保 存</button>
		</view>
		
	</view>
</template>

<script>
	var that;
	import _config from '../../config/index.js'; // 导入私有配置
	import checkUtil from '@/utils/checkUtil.js'
	import md5 from '@/common/lib/md5.min.js'
	import compressImage from '@/common/lib/util.js';
	import {formatTimeStap} from '@/utils/datetime.js'
	import {
		mapGetters
	} from 'vuex'
	const device = uni.getSystemInfoSync();
	export default {
		computed:{
			...mapGetters(['navHeight']),
		},
		data() {
			return {
				userInfo:uni.getStorageSync("userInfo"),
				statusBarHeight:Vue.prototype.StatusBar,
				idCard1 :'../../static/img/idcard1.png' ,
				idCard2 : '../../static/img/idcard2.png',
				name:'',
				birthday:'',
				idCard:'',
				province:'',
				city:'',
				district:'',
				address:'',
				user:'',
				avatar:'',
				sexArray:['男','女'],
				sexIndex:'0',
				//省份
				provinceList:[{'regionName':'请选择省份'}],
				provinceIndex:0,
				//城市
				cityList:[{'regionName':'请选择城市'}],
				cityIndex: 0,
				//市区
				districtList:[{'regionName':'请选择市区'}],
				districtIndex: 0,
				provinceId:'',
				cityId:'',
				flag:true
			}
		},
		onLoad() {
			that = this;
			this.user = uni.getStorageSync("userInfo")
			this.name = this.userInfo.NAME
			var nowDate = new Date();
			var year = nowDate.getFullYear();
			var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
			: nowDate.getMonth() + 1;
			var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
			.getDate();
			var now = year + "-" + month + "-" + day;
			this.birthday = this.userInfo.BIRTHDAY||now
			this.avatar = that.user.AVATAR||_config.NGINX_SERVER + 'imgs/avatar/avatar.jpg';
			this.sexIndex=this.userInfo.SEX?this.userInfo.SEX-1:0
			this.idCard = this.userInfo.ID_CARD
			this.province = this.userInfo.PROVINCE
			this.city = this.userInfo.CITY
			this.address = this.userInfo.ADDRESS
			
			var idCard1 = this.userInfo.ID_CARD_POSITIVE
			var idCard2 = this.userInfo.ID_CARD_BACK
			if(idCard1!=''){
				this.idCard1=idCard1
			}
			if(idCard2!=''){
				this.idCard2=idCard2
			}
			this.$http.getRegion({
				parentId:"1"
			}).then((res)=>{
				if(res.code==1){
					that.provinceList=[{"regionName":"请选择省份"}].concat(res.result) 
					for(var i=0;i<that.provinceList.length;i++){
						if(that.provinceList[i].regionName == that.userInfo.PROVINCE){
							that.provinceIndex = i;
							that.provinceId = that.provinceList[i].id
							return;
						}
					}
				}
			})
		},
		watch:{
			provinceId(val) {
				this.$http.getRegion({
					parentId:that.provinceId
				}).then((res)=>{
					if(res.code==1){
						that.cityList=[{"regionName":"请选择城市"}].concat(res.result) 
						for(var i=0;i<that.cityList.length;i++){
							if(that.cityList[i].regionName == that.userInfo.CITY){
								that.cityIndex = i;
								that.cityId = that.cityList[that.cityIndex].id
								return;
							}
						}
					}
				})
			},
			cityId(val) {
				this.$http.getRegion({
					parentId:that.cityId
				}).then((res)=>{
					if(res.code==1){
						if(res.result.length==0){
							that.flag=false
							return;
						}
						that.flag=true
						that.districtList=[{"regionName":"请选择市区"}].concat(res.result) 
						for(var i=0;i<that.districtList.length;i++){
							if(that.districtList[i].regionName == that.userInfo.DISTRICT){
								that.districtIndex = i;
								return;
							}
						}
					}
				})
			}
		},
		methods: {
			async compressImageHandler(src){
				const tempPath = await compressImage(src,device.platform);
				return tempPath
			},
			bindSexChange: function(e) {
				this.sexIndex = e.target.value
			},
			bindDateChange: function(e) {
				this.birthday = e.target.value
			},
			bindProvinceChange: function(e) {
				this.provinceIndex = e.target.value
				that.cityIndex = 0
				that.districtIndex=0
				this.provinceId = this.provinceList[this.provinceIndex].id
			},
			bindCityChange: function(e) {
				this.cityIndex = e.target.value
				that.districtIndex = 0
				this.cityId = this.cityList[this.cityIndex].id
			},
			bindDistrictChange: function(e) {
				this.districtIndex = e.target.value
			},
			back(){
				uni.navigateBack();
			},
			changeAvatar(){
				uni.chooseImage({
					count:1,
					success:function(res){
						that.avatar = res.tempFilePaths[0];
					}
				})
			},
			selectImg1 : function() {
				uni.chooseImage({
					count:1,
					success:async function(res){
						that.idCard1 = await that.compressImageHandler(res.tempFilePaths[0]) ;
					}
				})
			},
			selectImg2 : function() {
				uni.chooseImage({
					count:1,
					success:async function(res){
						that.idCard2 =  await that.compressImageHandler(res.tempFilePaths[0]) ;
					}
				})
			},
			previewImg1 : function(){
				uni.previewImage({
					urls:[that.idCard1]
				});
			},
			previewImg2 : function(){
				uni.previewImage({
					urls:[that.idCard2]
				});
			},
			save : function(){
				if(this.avatar==""||this.avatar ==_config.NGINX_SERVER + 'imgs/avatar/avatar.jpg'){
					uni.showToast({title:"请选择头像", position:"bottom",icon:"none"});
					return;
				}
				if(this.name==""||this.name==undefined){
					uni.showToast({title:"请输入姓名", position:"bottom",icon:"none"});
					return;
				}
				if(this.birthday==""||this.birthday==undefined){
					uni.showToast({title:"请选择生日", position:"bottom",icon:"none"});
					return;
				}
				if(!checkUtil.checkIdCard(this.idCard)){
					uni.showToast({title:"请输入正确的身份证号", position:"bottom",icon:"none"});
					return;
				}
				if(this.provinceIndex==0){
					uni.showToast({title:"请选择省份", position:"bottom",icon:"none"});
					return;
				}
				if(this.cityIndex == 0){
					uni.showToast({title:"请选择城市", position:"bottom",icon:"none"});
					return;
				}
				if(this.districtIndex == 0&&this.flag==true){
					uni.showToast({title:"请选择市区", position:"bottom",icon:"none"});
					return;
				}
				if(this.address==""||this.address==undefined){
					uni.showToast({title:"请输入地址", position:"bottom",icon:"none"});
					return;
				}
				if(this.idCard1 == '../../static/img/idcard1.png' || this.idCard2 == '../../static/img/idcard2.png'){
					uni.showToast({title:"请选择身份证照片", position:"bottom",icon:"none"});
					return;
				}
				var imgs = [
					{"name":"avatar",
					"uri":that.avatar},
					{"name":"positive",
					"uri":that.idCard1},
					{"name":"back",
					"uri":that.idCard2}
				]
				uni.showLoading({title:"保存中..."});
				uni.uploadFile({
					url:_config.ipAddress+"app/updateUserInfo",
					header:{
						"token":uni.getStorageSync("token"),
						"currentTime":formatTimeStap(new Date())
					},
					sizeType: ['compressed'],  
					files:imgs,
					formData:{
						name:that.name,
						birthday:that.birthday,
						sex:String(Number(that.sexIndex)+1),
						idCard:that.idCard,
						province:that.provinceList[that.provinceIndex].regionName,
						city:that.cityList[that.cityIndex].regionName,
						district:that.districtList[that.districtIndex].regionName,
						address:that.address
					},
					success:(res)=>{
						res = JSON.parse(res.data)
						if(res.code==1){
							uni.removeStorageSync("myAvatar")
							uni.removeStorageSync("idcard1")
							uni.removeStorageSync("idcard2")
							uni.showToast({title:"保存成功！", position:"bottom",icon:"none"});
							var autoInfo = uni.getStorageSync("autoInfo")
							var params = {
								phone : '',
								password : '',
								loginType:"1"
							}
							if(autoInfo!=null){
								params.phone = autoInfo.phone;
								params.password = autoInfo.password;
							}
							that.$store.dispatch('login', params).then(res => {
								if (res.code === 1) {
									uni.setStorageSync("token",res.result.token)
								} else {
									uni.showToast({
										icon: 'none',
										position: 'center',
										title: "登录信息失效，请重新登录"
									});
									uni.reLaunch({
										url: '/pages/login/login',
									})
								}
							}).catch(() => {
							})
						}else{
							uni.showToast({title:res.message, position:"bottom",icon:"none"});
						}
					},
					fail(res) {
					}
				})
			}
		}
	}
</script>

<style>
.cu-item{
	height: 108rpx;
}
.content{
	color:#878A99;
}
.my_input{
	text-align: right;
	vertical-align: middle;
	width:500rpx
}
.grace-idcard-main{margin:20upx 30upx;}
.grace-idcard-desc{line-height:2em; background:#FFFFFF; padding:20upx; border-radius:10upx;}
.grace-idcard-text{line-height:2em; margin-top:30upx;}
.grace-idcard-items{background:#FFFFFF; padding:30upx 0; display:flex; margin:30upx 0; border-radius:10upx; align-items: flex-start;}
.grace-idcard-uper-btn{width:276upx; margin:0 60upx; background:#F1F1F1; padding-bottom:10upx; border-radius:10upx; text-align:center;}
.grace-idcard-uper-btn .img{width:100upx; height:100upx; margin:0 auto; margin-top:30upx;}
.grace-idcard-uper-btn .img image{width:100upx; height:100upx;}
.grace-idcard-uper-btn .text{width:100%; margin-top:10upx; text-align:center; line-height:2em;}
.grace-idcard-preview{width:50%; margin:0 30upx;}
.grace-idcard-preview image{
	width:100%;
	height: 200rpx;
}
.login-btn {
	border-radius: 0;
	background-color: #427EE3!important;
	color: #fff;
	width: 100%;
	height: 80rpx;
}
.save_btn{
	margin: 20rpx 30rpx;
}
</style>
